//
//  PhotoBrowserController.swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/5/5.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit
import SVProgressHUD

private let photoBrowserCellReuseIdentifier = "photoBrowserCellReuseIdentifier"
class PhotoBrowserController: UIViewController {

    var currentIndex: Int?
    
    var pictureURLs: [NSURL]?
    
    
    init(index: Int, urls: [NSURL])
    {
        super.init(nibName: nil, bundle: nil)
        
        currentIndex = index
        pictureURLs = urls
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
        
    }
    
    private func setupUI()
    {
        // 添加子控件
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        // 布局子控件
        closeBtn.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSize(width: 100, height: 35), offset: CGPoint(x: 10, y: -10))
        saveBtn.xmg_AlignInner(type: XMG_AlignType.BottomRight, referView: view, size: CGSize(width: 100, height: 35), offset: CGPoint(x: -10, y: -10))
        collectionView.frame = UIScreen.mainScreen().bounds
        
        // 设置数据源代理
        collectionView.dataSource = self
        // 注册cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: photoBrowserCellReuseIdentifier)
        
        collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "lclc")
        
        
        collectionView.contentOffset = CGPoint(x: UIScreen.mainScreen().bounds.size.width * CGFloat(currentIndex!), y: 0)
        print(collectionView.contentOffset)
    }
    
    /**
     关闭图片浏览器
     */
    func close()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    /**
     保存图片
     */
    func save()
    {
        // 拿到当前cell索引
        let index = collectionView.indexPathsForVisibleItems().last
        // 拿到cell
        let cell = collectionView.cellForItemAtIndexPath(index!) as! PhotoBrowserCell
        // 拿到图片
        let image = cell.iconView.image
        UIImageWriteToSavedPhotosAlbum(image!, self, #selector(PhotoBrowserController.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    /**
     保存图片回调方法
     */
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject)
    {
        if error != nil
        {
            SVProgressHUD.showErrorWithStatus("保存失败", maskType: SVProgressHUDMaskType.Black)
        }
        else
        {
            SVProgressHUD.showSuccessWithStatus("保存成功", maskType: SVProgressHUDMaskType.Black)
        }
    }
    
    // MARK: - 懒加载
    private lazy var closeBtn: UIButton = {
       let btn = UIButton()
        btn.setTitle("关闭", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.darkGrayColor()
        btn.addTarget(self, action: #selector(PhotoBrowserController.close), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    private lazy var saveBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.darkGrayColor()
        btn.addTarget(self, action: #selector(PhotoBrowserController.save), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserLayout())
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension PhotoBrowserController: UICollectionViewDataSource, PhotoBrowserCellDelegate
{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(photoBrowserCellReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell
        cell.backgroundColor = UIColor.randomColor()
        cell.imageURL = pictureURLs![indexPath.item]
        cell.photoBrowserCellDelegate = self
        return cell
    }
    
    func photoBrowserCellDidClose(cell: PhotoBrowserCell) {
        dismissViewControllerAnimated(true, completion: nil)
    }
}

class PhotoBrowserLayout: UICollectionViewFlowLayout
{
    override func prepareLayout()
    {
        itemSize = UIScreen.mainScreen().bounds.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
    }
}
